package com.ks.winterwarmimage;

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;

import androidx.annotation.IntDef;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.ks.winterwarmimage.mqtt.MqttMag;
import com.ks.winterwarmimage.mqtt.MsgMqttService;
import com.ks.winterwarmimage.utils.StatusBarUtil;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class BaseActivity extends AppCompatActivity {
    private static final String TAG = BaseActivity.class.getSimpleName();
    /**请求码*/
    protected static final int REQUEST_CODE=100;
    /**返回码*/
    protected static final int RESULT_CODE=100;
    /**Mqtt服务对象*/
    private MsgMqttService mMsgMqttService=null;
    /**Mqtt服务状态*/
    private boolean mMqttServiceConnectedState=false;
    @IntDef({MqttCommandState.MQTT_DISCONNECT,MqttCommandState.MQTT_CONNECT,
            MqttCommandState.MQTT_CONNECT_SUCCESS,MqttCommandState.MQTT_CONNECT_FAIL})
    @Retention(RetentionPolicy.SOURCE)
    /**MQTT连接状态枚举*/
    public @interface MqttCommandState {
        /**MQTT连接断开*/
        int MQTT_DISCONNECT=0;
        /**MQTT连接开始*/
        int MQTT_CONNECT=1;
        /**MQTT连接成功*/
        int MQTT_CONNECT_SUCCESS=2;
        /**MQTT连接失败*/
        int MQTT_CONNECT_FAIL=3;
    }
    /**
     * MQTT服务状态改变
     */
    protected void onMqttServiceConnected(){}
    /**
     * MQTT连接改变
     * @param commandState 连接状态。范围在{@link MqttCommandState}之间
     */
    protected void onMqttConnectionChange(@MqttCommandState int commandState){}
    protected void onMessageArrived(MqttMag message){}

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        StatusBarUtil.setNoTitle(this);
        StatusBarUtil.setStatusBarMode(this,true,getColor(R.color.white));
    }
    /**
     * 检查并注册权限
     * @param ble 注册ble权限
     * @return
     */
    protected boolean checkSelfBlePermission(boolean ble){
        if (Build.VERSION.SDK_INT <Build.VERSION_CODES.M) { //Android 6.以下版本
            return true;
        }else{
            //处理动态权限(位置权限)
            List<String> mPermissionList = new ArrayList<>();
            if (this.checkSelfPermission(android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
                mPermissionList.add(android.Manifest.permission.ACCESS_COARSE_LOCATION);
            if (this.checkSelfPermission(android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)
                mPermissionList.add(android.Manifest.permission.ACCESS_FINE_LOCATION);
            if (this.checkSelfPermission(android.Manifest.permission.ACCESS_WIFI_STATE) != PackageManager.PERMISSION_GRANTED)
                mPermissionList.add(android.Manifest.permission.ACCESS_WIFI_STATE);
            if (this.checkSelfPermission(android.Manifest.permission.CHANGE_WIFI_STATE) != PackageManager.PERMISSION_GRANTED)
                mPermissionList.add(android.Manifest.permission.CHANGE_WIFI_STATE);
            if (this.checkSelfPermission(android.Manifest.permission.CHANGE_NETWORK_STATE) != PackageManager.PERMISSION_GRANTED)
                mPermissionList.add(android.Manifest.permission.CHANGE_NETWORK_STATE);
            //Android 版本大于等于 Android12
            if (Build.VERSION.SDK_INT >=Build.VERSION_CODES.S && ble) {
                if (this.checkSelfPermission(android.Manifest.permission.BLUETOOTH_SCAN) != PackageManager.PERMISSION_GRANTED)
                    mPermissionList.add(android.Manifest.permission.BLUETOOTH_SCAN);
                if (this.checkSelfPermission(android.Manifest.permission.BLUETOOTH_ADVERTISE) != PackageManager.PERMISSION_GRANTED)
                    mPermissionList.add(android.Manifest.permission.BLUETOOTH_ADVERTISE);
                if (this.checkSelfPermission(android.Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED)
                    mPermissionList.add(Manifest.permission.BLUETOOTH_CONNECT);
            }
            if(mPermissionList.size()>0){
                requestPermissions(mPermissionList.toArray(new String[0]),REQUEST_CODE);
            }else{
                return true;
            }
        }
        return false;
    }
    /**
     * 绑定MQTT服务
     */
    protected void bindMqttService(){
        final IntentFilter actionFilter = new IntentFilter();
        actionFilter.addAction(MsgMqttService.BIN_SERVICE_SUCCESS);
        actionFilter.addAction(MsgMqttService.MQTT_CONNECT);
        actionFilter.addAction(MsgMqttService.MQTT_CONNECT_SUCCESS);
        actionFilter.addAction(MsgMqttService.MQTT_CONNECT_FAIL);
        actionFilter.addAction(MsgMqttService.MQTT_MESSAGE_ARRIVED);
        MsgMqttService.bindService(this,actionFilter,updateMqttReceiver);
    }
    /**
     * 移除MQTT服务
     */
    protected void unbindMqttService(){
        MsgMqttService.unBindService(this,updateMqttReceiver);
    }

    /**
     * 移除广播接收
     */
    protected void unMqttBroadcastReceiver(){
        MsgMqttService.unRegisterReceiver(this,updateMqttReceiver);
    }
    private BroadcastReceiver updateMqttReceiver=new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if(MsgMqttService.BIN_SERVICE_SUCCESS.equals(action)) {
                onMqttServiceConnected();         //触发服务连接事件
            }else if(MsgMqttService.MQTT_CONNECT.equals(action)){
                onMqttConnectionChange(MqttCommandState.MQTT_CONNECT); //触发连接状态改变事件
            }else if(MsgMqttService.MQTT_CONNECT_SUCCESS.equals(action)){
                onMqttConnectionChange(MqttCommandState.MQTT_CONNECT_SUCCESS); //触发连接状态改变事件
            }else if(MsgMqttService.MQTT_CONNECT_FAIL.equals(action)){
                onMqttConnectionChange(MqttCommandState.MQTT_CONNECT_FAIL);  //触发连接状态改变事件
            }else if(MsgMqttService.MQTT_DISCONNECT.equals(action)){
                onMqttConnectionChange(MqttCommandState.MQTT_DISCONNECT);    //触发连接状态改变事件
            }else if(MsgMqttService.MQTT_MESSAGE_ARRIVED.equals(action)) {
                String topic = intent.getStringExtra("topic");
                if (topic != null) {
                    byte[] payload = intent.getByteArrayExtra("payload");
                    MqttMag mqttMag = new MqttMag();
                    mqttMag.setTopic(topic);
                    if (payload != null) {
                        mqttMag.setMessage(payload);
                        mqttMag.setQoS((byte) intent.getIntExtra("qos", 0));
                        mqttMag.setRetained(intent.getBooleanExtra("retained", false));
                        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        mqttMag.setDateTime(format.format(new Date()));
                        onMessageArrived(mqttMag);        //触发消息到达事件
                    }
                }
            }
        }
    };
}
